# # -*- coding: utf-8 -*-
# # @Date    : 2024/2/22
# # @Author  : zouy
# # @Email: 874112501@qq.com
import os

import requests
from PIL import Image

DIR_PATH = os.path.dirname(os.path.abspath(__file__))


def img2array(img_path):
    """将验证码图片地址进行数组还原
    js位置：https://cdn.dingxiang-inc.com/ctu-group/captcha-js/5.1.47/basic-Captcha-js.js
     {
        "el": t,
        "width": c,  # 380  # 原图：400*200
        "height": s,  # 165
        "src": i,  # "https://static.dingxiang-inc.com/picture/dx/hXzhKbVylj/zib3/cff23b49eef24073b11ad734bf5fc23c.webp"
        "ranges": r,  # 生成的数组
        "isSaaS": o  # true
    }
    """
    img_id = img_path.split('/')[-1].split('.')[0]
    array = []
    for s, char in enumerate(img_id):
        d = ord(char)
        while d % 32 in array:
            d += 1
        array.append(d % 32)
    return array


def array_restore(arr, img_path, new_img_name='bg_restore.png'):
    """乱序图还原数组(图片与数组一一对应,数组 对应上方的url背景图)

    r = [ 24, 3, 19, 25, 23, 4, 5, 22, 6, 7, 16, 1, 20, 26, 17, 8, 2, 18, 9, 21, 10, 27, 11, 12, 28, 13, 29, 30, 31, 0, 14, 15 ]
    a = int(width / len(r))  # 12
    # x轴()      y轴(固定0)  宽(int(height/len(r))=12 固定12)  高(height固定200)
    point = [idx * int(height/len(r)),    0,      12,                          200]
    # CanvasRenderingContext2D.drawImage([<img>, r[idx] * int(height/len(r)) , 0, 12, 200,  ...point ])
    """
    _img = Image.open(img_path)

    # 创建一个新的背景图
    new_img = Image.new('RGB', (400, 200))  # 宽400 高200

    for index in range(len(arr)):
        c = arr[index] * 12
        # 从背景图中扣出相应的小图
        l = _img.crop((c, 0, c + 12, 200))  # 图片剪切crop(x,y,x1,y1) 四个坐标
        # 将扣出的小图 还原到正确的位置
        new_x = index * 12
        new_img.paste(l, (new_x, 0))
    new_img.paste(_img.crop((384, 0, 400, 200)), (384, 0))  # 最后的边框 32*12=384
    new_img.save(os.path.join(os.path.dirname(img_path), new_img_name))


def download_img(file_name, *, url):
    """下载验证码图片"""
    resp = requests.get(url, headers={
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"})
    pic_dir = os.path.join(DIR_PATH, 'pic')
    if not os.path.exists(pic_dir):
        os.mkdir(pic_dir)
    path = os.path.join(pic_dir, file_name)
    with open(path, mode="wb") as f:
        f.write(resp.content)
    return path


def get_slide_distance(fg_name, bg_name):
    """获取滑块距离"""
    import ddddocr
    det = ddddocr.DdddOcr(det=False, ocr=False, show_ad=False)
    with open(os.path.join(DIR_PATH, 'pic', fg_name), 'rb') as f:
        target_bytes = f.read()
    with open(os.path.join(DIR_PATH, 'pic', bg_name), 'rb') as f:
        background_bytes = f.read()

    res = det.slide_match(target_bytes, background_bytes)

    print(res)
    return res['target'][0]


static_url = 'https://static.dingxiang-inc.com/picture'
if __name__ == '__main__':
    p1_url = "/dx/nFJUb0neuT/zib3/e6aa80dead9942578c7964ca55aa4023.webp"
    p2_url = "/dx/nFJUb0neuT/zib3/462ac40fd83447afb3869f4645d2f7ff.webp"
    bg_img_name = 'bg.png'  # 背景图
    front_img_name = 'front.png'  # 滑块图
    new_img_name = 'bg_restore.png'  # 还原之后的图片名
    #
    # # 背景图片请求下载
    # bg_path = download_img(bg_img_name, url=static_url + p1_url)
    # # 背景图数组本地还原
    # img_array = img2array(p1_url)
    # print(img_array)
    #
    # # 背景图片本地重新生成
    # array_restore(img_array, bg_path, new_img_name=new_img_name)
    # # 下载滑块图
    # download_img(front_img_name, url=static_url + p2_url)

    # 缺口距离识别 （本地图片宽400，网站图片宽380）
    print(get_slide_distance(front_img_name, new_img_name) * 380 / 400)
